import { UploadOutlined } from '@ant-design/icons'
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  message,
  Row,
  Select,
  Spin,
  Cascader,
  Upload,
  ConfigProvider
} from 'antd'
import React, { useEffect, useState } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { connect } from 'umi'
import moment from 'moment'
import styles from '@/pages/Info/Edit/style.less'
import { genderList, healthsList, inOrgList, maritalList, nationList, regionList, yesOrNoList } from '@/utils/constant'
import { getNativeplace } from '@/pages/Info/service'
import EducationTableForm from './components/EducationTableForm'
import SocietyTableForm from './components/SocietyTableForm'
import InOrgNameTableForm from './components/InOrgNameTableForm'
import FamilyTableForm from './components/FamilyTableForm'
import FooterToolbar from '@/pages/Info/Edit/components/FooterToolbar'
import { getEmployeeByIdAuth, updateMainInfo } from './service'
import { getQueryString } from '@/utils/utils'
import zh_CN from 'antd/lib/locale-provider/zh_CN'
import {getUploadUrl} from "@/utils/upload";

const { Option } = Select
const FormItem = Form.Item

const colStyle = {
  xl: {
    span: 6,
    offset: 1,
  },
  lg: 8,
  md: 12,
  sm: 24,
  xs: 24,
}

const Invitation = ({ submitting }) => {

  const [form] = Form.useForm()
  const [error, setError] = useState([])
  const [nativePlaces, setNativePlaces] = useState([])
  const [fileName, setFileName] = useState(null)
  const [imageList, setImageList] = useState({})
  const [resInfo, setResInfo] = useState()
  const [employeeId, setEmployeeId] = useState(getQueryString('oid'))

  const fileProps = {
    name: 'file',
    action: getUploadUrl(),
    data: { name: fileName, catlog: 'personal' },
    beforeUpload (file) {
      if (file.size/1024 > 10000) {
        message.error(`上传文件大小不能超过10M！`);
        return false;
      }
      setFileName(file.name)
    },

  }

  useEffect(() => {
    reloadData()
    getNativeplaceList()
  }, [])

  const getNativeplaceList = () => {
    getNativeplace().then((res = []) => {
      setNativePlaces(res)
    })
  }

  const reloadData = () => {
    getEmployeeByIdAuth(employeeId).then((res) => {
      setResInfo(res)
      setEmployeeId(res.oid)
      let data = {
        ...res,
        birthday: res.birthday ? moment(res.birthday) : undefined,
        beginworkdate: res.beginworkdate ? moment(res.beginworkdate) : undefined,
        hiredate: res.hiredate ? moment(res.hiredate) : undefined,
        orgId: res.orgId ? parseInt(res.orgId) : undefined,
        unitId: res.unitId ? parseInt(res.unitId) : undefined,
        isManagementTrainee: parseInt(res.isManagementTrainee),
      }
      if (data) {
        let { nativeplace, nativeplaceProvince, ...resData } = data
        let showNativeplace = ['']
        if (nativeplace && nativeplace !== nativeplaceProvince) {
          showNativeplace = [nativeplaceProvince, nativeplace]
        } else if (nativeplace && nativeplace === nativeplaceProvince) {
          showNativeplace = [nativeplace]
        }
        setImageList({
          photoUrl: data.photoUrl ? [{ uid: '1', name: data.photoUrl.split('----')[1], status: 'done', url: data.photoUrl }] : [],
          idcardImgs: data.idcardImgs ? data.idcardImgs.map((item,index)=>({ uid: index, name: item.split('----')[1], status: 'done', url: item })) : [],
          dimissionUrl: data.dimissionUrl ? [{ uid: '1', name: data.dimissionUrl.split('----')[1], status: 'done', url: data.dimissionUrl }] : [],
          graduationUrl: data.graduationUrl ? [{ uid: '1', name: data.graduationUrl.split('----')[1], status: 'done', url: data.graduationUrl }] : [],
          degreeUrl: data.degreeUrl ? [{ uid: '1', name: data.degreeUrl.split('----')[1], status: 'done', url: data.degreeUrl }] : [],
          healthUrl: data.healthUrl ? [{ uid: '1', name: data.healthUrl.split('----')[1], status: 'done', url: data.healthUrl }] : [],
          oldSalaryRecordUrl: data.oldSalaryRecordUrl ? data.oldSalaryRecordUrl.map((item,index)=>({ uid: index, name: item.split('----')[1], status: 'done', url: item })) : [],
          credential: data.credential ? data.credential.map((item,index)=>({ uid: index, name: item.split('----')[1], status: 'done', url: item })) : [],
          attachments: data.attachments ? data.attachments.map((item,index)=>({ uid: index, name: item.split('----')[1], status: 'done', url: item })) : [],
        })
        form.setFieldsValue({ ...resData, nativeplace: showNativeplace })
      }
    })
  }

  const onFinish = (values) => {
    let { nativeplace, ...data } = values
    data.nativeplaceProvince = nativeplace[0]
    if (nativeplace.length > 1) {
      data.nativeplace = nativeplace[1]
    } else {
      data.nativeplace = nativeplace[0]
    }
    let postData = {
      ...data,
      oid: employeeId,
      updateHireDate: moment(resInfo.hiredate).format('YYYY-MM-DD'),
      photoUrl: imageList.photoUrl[0]?.response || imageList.photoUrl[0]?.url,
      idcardImgs: imageList.idcardImgs?.map(item => item.response || item.url),
      dimissionUrl: imageList.dimissionUrl[0]?.response || imageList.dimissionUrl[0]?.url,
      graduationUrl: imageList.graduationUrl[0]?.response || imageList.graduationUrl[0]?.url,
      degreeUrl: imageList.degreeUrl[0]?.response || imageList.degreeUrl[0]?.url,
      healthUrl: imageList.healthUrl[0]?.response || imageList.healthUrl[0]?.url,
      oldSalaryRecordUrl: imageList.oldSalaryRecordUrl?.map(item => item.response || item.url),
      credential: imageList.credential?.map(item => item.response || item.url),
      attachments: imageList.attachments?.map(item => item.response || item.url),
    }
    updateMainInfo(postData).then(res => {
      if (res.flag) {
        message.success('信息录入成功！')
      } else {
        message.error(`信息录入失败，${res.error}`)
      }
    })
  }

  const onFinishFailed = (errorInfo) => {
    setError(errorInfo.errorFields)
  }

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  }

  const setNativePlaceLabel = (label) => {
    if (typeof label !== 'string') {
      return label.join('')
    } else {
      return [label].join('')
    }
  }

  const uploadButton = (
    <Button icon={<UploadOutlined/>}>点击上传文件</Button>
  )

  const onChangeImageList = (e, name) => {
    setImageList({
      ...imageList,
      [name]: e.fileList
    })
  }

  return (
    resInfo ?
      <ConfigProvider locale={zh_CN}>
        <Form
          form={form}
          layout="vertical"
          hideRequiredMark
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <div className='info-edit' style={{ background: '#f0f2f5' }}>
            <div style={{ height: '486px', width: '100%', display: 'flex', justifyContent: 'center',overflow:'hidden' }}>
              <img style={{ objectFit: 'cover' }} height={486} src={require('@/assets/banner3000.png')}/>
            </div>
            <PageHeaderWrapper title={resInfo.name ?
            <div style={{ paddingLeft: '24px' }}>{resInfo.name}, 您好。为方便您的入职流程办理，请填写以下信息：</div>:'加载中...'}>
              <Card title="基本信息" className={styles.card} bordered={false}>
                <Row gutter={24}>
                  <Col {...colStyle}>
                    <FormItem label={'姓名'} name="name">
                      <Input placeholder="请输入"/>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'性别'} name="gender">
                      <Select placeholder="请选择">
                        {genderList.map((item, index) => {
                          return (
                            <Option value={`${item.value}`} key={item.value}>
                              {item.label}
                            </Option>
                          )
                        })}
                      </Select>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'身份证'} name="idcard">
                      <Input placeholder="请输入"/>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'民族'} name="nationality">
                      <Select placeholder="请选择" showSearch filterOption={filterOption}>
                        {nationList.map((item, index) => {
                          return (
                            <Option value={`${item.value}`} key={item.value}>
                              {item.label}
                            </Option>
                          )
                        })}
                      </Select>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'籍贯'} name="nativeplace">
                      <Cascader fieldNames={{ label: 'title', value: 'title', children: 'children' }}
                                displayRender={(label) => setNativePlaceLabel(label)} placeholder="请输入"
                                options={nativePlaces}/>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'国籍'} name="nation">
                      <Select placeholder="请选择" showSearch filterOption={filterOption}>
                        {regionList.map((item, index) => {
                          return (
                            <Option value={`${item.value}`} key={item.value}>
                              {item.label}
                            </Option>
                          )
                        })}
                      </Select>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'政治面貌'} name="polity">
                      <Select placeholder="请选择" showSearch filterOption={filterOption}>
                        {inOrgList.map((item, index) => {
                          return (
                            <Option value={`${item.value}`} key={item.value}>
                              {item.label}
                            </Option>
                          )
                        })}
                      </Select>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'户口所在地'} name="regresidence">
                      <Input placeholder="请输入"/>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'家庭住址'} name="address">
                      <Input placeholder="请输入"/>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'健康状态'} name="healthstatus">
                      <Select placeholder="请选择" showSearch filterOption={filterOption}>
                        {healthsList.map((item, index) => {
                          return (
                            <Option value={`${item.value}`} key={item.value}>
                              {item.label}
                            </Option>
                          )
                        })}
                      </Select>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'电子邮箱'} name="privatemail">
                      <Input placeholder="请输入"/>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'生日'} name="birthday">
                      <DatePicker placeholder="请选择日期" style={{ width: '100%' }}/>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'手机'} name="mobile">
                      <Input placeholder="请输入"/>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'参加工作时间'} name="beginworkdate">
                      <DatePicker placeholder="请选择日期" style={{ width: '100%' }}/>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'婚姻状况'} name="marital">
                      <Select placeholder="请选择">
                        {maritalList.map((item, index) => {
                          return (
                            <Option value={`${item.value}`} key={item.value}>
                              {item.label}
                            </Option>
                          )
                        })}
                      </Select>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'是否退伍兵'} name="disbandment">
                      <Select placeholder="请选择">
                        {yesOrNoList.map((item, index) => {
                          return (
                            <Option value={`${item.value}`} key={item.value}>
                              {item.label}
                            </Option>
                          )
                        })}
                      </Select>
                    </FormItem>
                  </Col>

                  <Col {...colStyle}>
                    <FormItem label={'退伍军人编号'} name="veteranNum">
                      <Input placeholder="请输入退伍军人编号"/>
                    </FormItem>
                  </Col>
                </Row>
              </Card>

              <Card title="教育经历" bordered={false} style={{ marginBottom: 24 }}>
                <FormItem name="employeeEducation">
                  <EducationTableForm educationList={resInfo?.employeeEducation} employeeId={employeeId}/>
                </FormItem>
              </Card>

              <Card title="工作经历" bordered={false} style={{ marginBottom: 24 }}>
                <FormItem name="employeeSociety">
                  <SocietyTableForm societyList={resInfo?.employeeSociety} employeeId={employeeId}/>
                </FormItem>
              </Card>

              <Card title="行政党派信息" bordered={false} style={{ marginBottom: 24 }}>
                <FormItem name="employeeInorgname">
                  <InOrgNameTableForm inOrgNameList={resInfo?.employeeInorgname} employeeId={employeeId}/>
                </FormItem>
              </Card>

              <Card title="家庭成员信息" bordered={false} style={{ marginBottom: 24 }}>
                <FormItem name="familyMember">
                  <FamilyTableForm familyList={resInfo?.familyMember} employeeId={employeeId}/>
                </FormItem>
              </Card>

              <div style={{ paddingBottom: '60px' }}>

                <Card bodyStyle={{ paddingButton: '60px' }} title="附件信息" bordered={false}>
                  <Row gutter={24}>
                    <Col span={8}>
                      <FormItem labelAlign='right' lableCol={7} label='个人一寸照片'>
                        <Upload {...fileProps} fileList={imageList.photoUrl}
                                onChange={e => onChangeImageList(e, 'photoUrl')}>
                          {(!imageList.photoUrl || imageList.photoUrl.length < 1) && uploadButton}
                        </Upload>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem labelAlign='right' lableCol={7} label='身份证正反面照片'>
                        <Upload {...fileProps} fileList={imageList.idcardImgs}
                                onChange={e => onChangeImageList(e, 'idcardImgs')}>
                          {(!imageList.idcardImgs || imageList.idcardImgs.length < 1) && uploadButton}
                        </Upload>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem labelAlign='right' lableCol={7} label='离职证明'>
                        <Upload {...fileProps} fileList={imageList.dimissionUrl}
                                onChange={e => onChangeImageList(e, 'dimissionUrl')}>
                          {(!imageList.dimissionUrl || imageList.dimissionUrl.length < 1) && uploadButton}
                        </Upload>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem labelAlign='right' lableCol={7} label='毕业证'>
                        <Upload {...fileProps} fileList={imageList.graduationUrl}
                                onChange={e => onChangeImageList(e, 'graduationUrl')}>
                          {(!imageList.graduationUrl || imageList.graduationUrl.length < 1) && uploadButton}
                        </Upload>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem labelAlign='right' lableCol={7} label='学位证'>
                        <Upload {...fileProps} fileList={imageList.degreeUrl}
                                onChange={e => onChangeImageList(e, 'degreeUrl')}>
                          {(!imageList.degreeUrl || imageList.degreeUrl.length < 1) && uploadButton}
                        </Upload>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem labelAlign='right' lableCol={7} label='体检报告'>
                        <Upload {...fileProps} fileList={imageList.healthUrl}
                                onChange={e => onChangeImageList(e, 'healthUrl')}>
                          {(!imageList.healthUrl || imageList.healthUrl.length < 1) && uploadButton}
                        </Upload>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem labelAlign='right' lableCol={7} label='银行流水/薪资证明'>
                        <Upload {...fileProps} fileList={imageList.oldSalaryRecordUrl}
                                onChange={e => onChangeImageList(e, 'oldSalaryRecordUrl')}>
                          {(!imageList.oldSalaryRecordUrl || imageList.oldSalaryRecordUrl.length < 1) && uploadButton}
                        </Upload>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem labelAlign='right' lableCol={7} label='职称证书'>
                        <Upload {...fileProps} fileList={imageList.credential}
                                onChange={e => onChangeImageList(e, 'credential')}>
                          {(!imageList.credential || imageList.credential.length < 1) && uploadButton}
                        </Upload>
                      </FormItem>
                    </Col>

                    <Col span={8}>
                      <FormItem labelAlign='right' lableCol={7} label='其他附件'>
                        <Upload {...fileProps} fileList={imageList.attachments}
                                onChange={e => onChangeImageList(e, 'attachments')}>
                          {(!imageList.attachments || imageList.attachments.length < 1) && uploadButton}
                        </Upload>
                      </FormItem>
                    </Col>
                  </Row>
                </Card>
              </div>


            </PageHeaderWrapper>
          </div>
          <FooterToolbar>
            <Button type="primary" size="large" onClick={() => form?.submit()} loading={submitting}>保存</Button>
          </FooterToolbar>
        </Form> </ConfigProvider> : <div className='spin-block'><Spin size="large"/></div>
  )
}

export default connect(({ infoAndEdit, infoModel, loading }) => ({
  infoModel,
  infoAndEdit,
}))(Invitation)
